package o2o.business.sms;


import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.MongoDaoImpl;
import o2o.dao.PO.user.UserInfo;
import o2o.system.Common;

import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 短信服务(判断是否可以发送短信)
 *
 * @author Administrator
 */
public class SmsBusiness {
    private int currDayCounts = 10;        //注册用户，一天最多接受10条短信
    private int interval = 1;            //两次短信发送间隔  1分钟

    private SmsBusiness() {
    }

    private static SmsBusiness single = new SmsBusiness();

    public static SmsBusiness getInstance() {
        if (single == null) {
            single = new SmsBusiness();
        }
        return single;
    }

    /**
     * 判断用户今天是否还可以接收短信
     *
     * @param username
     * @return
     */
    public boolean canSend(String username) throws SmsUserInfoException {
        if (username == null) {
            return false;
        }
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(username);

        //查询mongo，当前用户今天发送数量
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("username", username);
        List<HashMap<String, Object>> list = MongoDaoImpl.getInstance()
                .find(UserSMSInfoParams.MonUserSMSDB, UserSMSInfoParams.MonUserSMSInfo, map, 1);
        if (list == null || list.size() < 1) {
            return true;
        }
        HashMap<String, Object> mapData = list.get(0);
        //上次的发送时间如果为空，则可以发送
        if (!mapData.containsKey(UserSMSInfoParams.lastSendTime)) {
            return true;
        }
        //判断上次的发送时间和现在的间隔
        if (new Date().getTime() - Long.parseLong(mapData.get(UserSMSInfoParams.lastSendTime).toString()) < interval * 60 * 1000) {
            throw new SmsUserInfoException("发送太快，请稍等之后再发送");
        }

        //当前发送时间为空。理论是不可能出现的，出现的时候允许发送
        if (!mapData.containsKey(UserSMSInfoParams.currDayDate)) {
            return true;
        }
        //不是当前的时间，允许发送
        if (!mapData.get(UserSMSInfoParams.currDayDate).toString().equals(Common.sdfDate.format(new Date()))) {
            return true;
        }
        //当前发送条数不存在，允许发送
        if (!mapData.containsKey(UserSMSInfoParams.currDayCounts)) {
            return true;
        }
        //注册的时候，判断条数是否少于10条
        if (Long.parseLong(mapData.get(UserSMSInfoParams.currDayCounts).toString()) <= currDayCounts) {
            //当前发送条数没超出限制，允许发送
            return true;
        } else {
            throw new SmsUserInfoException("当前用户发送短信数量已超过限制");
        }

    }
}
